//
//  DDBossWorkDetailViewController.m
//  DingDongZP
//
//  Created by Jyh on 16/5/9.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDBossWorkDetailViewController.h"
#import "DDBossPublishJobViewController.h"
#import "DDJobsService.h"
#import "DDShareView.h"
#import "WXApi.h"
#import "DDCommonCell.h"
#import "DDJobDetailCell.h"
#import "DDBossDetailCell.h"
#import "DDTeamDescriptionCell.h"
#import "DDJobDescriptionCell.h"
#import "DDCompanyInfoCell.h"
#import "DDBossJobService.h"
#import "DDPublishInfoModel.h"
#import "DDShareManager.h"
#import "DDShareModel.h"


#define kJobDetailCellHeight          @140
#define kBossDetailCellHeight         @88
#define kTeamDescriptionCellHeight    @145
#define kJobDescriptionCellHeight     @186
#define kCompanyInfoCellHeight        @170

@interface DDBossWorkDetailViewController ()

@property (strong, nonatomic) DDJobsService *jobService;
@property (strong, nonatomic) DDBossJobService *bossJobService;

@property (strong, nonatomic) DDShareView *shareView;
@property (weak, nonatomic) IBOutlet UIView *tooView;
@property (weak, nonatomic) IBOutlet UIButton *editButton;
@property (weak, nonatomic) IBOutlet UIButton *hideButton;

@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (weak, nonatomic) IBOutlet UILabel *seeLabel;
@property (weak, nonatomic) IBOutlet UILabel *likeLabel;
@property (weak, nonatomic) IBOutlet UILabel *shareLabel;

@property (strong, nonatomic) NSMutableArray *rowHeightArray;

@property (strong, nonatomic) DDJobsDetail *jobsDetailModel;

- (IBAction)editButtonClick:(UIButton *)sender;
- (IBAction)hideButtonClick:(UIButton *)sender;

//@property (strong, nonatomic) LDBossPositionHeaderView *tableHeaderView;

@end

@implementation DDBossWorkDetailViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.rowHeightArray = [[NSMutableArray alloc] init];
        self.jobService = [[DDJobsService alloc] init];
        self.bossJobService = [[DDBossJobService alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpView];
    [self setUpData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryJobDetailInfo) name:NOTI_BOSS_EDIT_PUBLISHINFO object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTI_BOSS_EDIT_PUBLISHINFO object:nil];
}

- (DDShareView *)shareView
{
    if (!_shareView) {
        _shareView = (DDShareView *)[[NSBundle mainBundle] loadNibNamed:@"DDShareView" owner:self options:nil].firstObject;
    }
    
    return _shareView;
}

- (void)setUpView
{
    [self addRightButtonItemWithImage:[UIImage imageNamed:@"common_nav_share"] action:@selector(shareButtonClick)];
    
    [self.view bringSubviewToFront:self.tooView];
    [self.view bringSubviewToFront:self.headerView];
    self.tooView.layer.borderWidth = 1;
    self.tooView.layer.borderColor = COLOR_BORDER_GRAY.CGColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
//    self.tableView.tableHeaderView = self.tableHeaderView;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"DDJobDetailCell" bundle:nil] forCellReuseIdentifier:@"DDJobDetailCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DDBossDetailCell" bundle:nil] forCellReuseIdentifier:@"DDBossDetailCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DDTeamDescriptionCell" bundle:nil] forCellReuseIdentifier:@"DDTeamDescriptionCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DDJobDescriptionCell" bundle:nil] forCellReuseIdentifier:@"DDJobDescriptionCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DDCompanyInfoCell" bundle:nil] forCellReuseIdentifier:@"DDCompanyInfoCellID"];
    
}

//tableview head
//-(LDBossPositionHeaderView *)tableHeaderView {
//    
//    if (_tableHeaderView == nil) {
//        
//        _tableHeaderView = [[LDBossPositionHeaderView alloc]init];
//        _tableHeaderView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 80);
//        _tableHeaderView.backgroundColor = COLOR_WHITE;
//    }
//    
//    return _tableHeaderView;
//}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    WEAKSELF
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(weakSelf.view);
        make.edges.equalTo(weakSelf.view).with.insets(UIEdgeInsetsMake(0, 0, 50, 0));
    }];
}

- (void)setUpData
{
    self.rowHeightArray = [NSMutableArray arrayWithArray:@[kJobDetailCellHeight,kBossDetailCellHeight,kTeamDescriptionCellHeight,kJobDescriptionCellHeight,kCompanyInfoCellHeight]];
    
    [self queryJobDetailInfo];
    
}

#pragma mark - evnets
//分享
- (void)shareButtonClick
{
    DDShareModel *shareModel = [[DDShareModel alloc] init];

    shareModel.shareH5 = [DDAPIGenerate h5URLWithPath:_jobDetail.shareh5];
    shareModel.shareLogoUrl = [DDAPIGenerate imageURLWithPath:_jobDetail.logo];
    
    shareModel.shareTitle_SMS = _jobDetail.sharetitle_sms.length > 0 ? _jobDetail.sharetitle_sms : @"短信";
    shareModel.shareTitle_WeiBo = _jobDetail.sharetitle_weibo.length > 0 ? _jobDetail.sharetitle_weibo : @"微博";
    shareModel.shareTitle_WeiXin = _jobDetail.sharetitle_weixin.length > 0 ? _jobDetail.sharetitle_weixin : @"微信";
    
    shareModel.shareDesc = _jobDetail.sharedesc;
    
    self.shareView.shareModel = shareModel;
    
    [_shareView show];
    
    
}

- (void)shareCancelButtonOnClick:(UIButton *)button
{
    [self.shareView hide];
}

- (IBAction)editButtonClick:(UIButton *)sender {

    DDPublishInfoModel *model = [[DDPublishInfoModel alloc] init];
    if (self.jobDetail) {
        model.category_id = self.jobDetail.categoryid;
        model.category_name = self.jobDetail.category;
        
        model.job_title = self.jobDetail.jobtitle;
        model.salary_id = self.jobDetail.salaryid;
        model.salary_name = self.jobDetail.salary;
        model.job_attraction = self.jobDetail.jobattraction;
        model.experience_id = self.jobDetail.experienceid;
        model.experience_name = self.jobDetail.experience;
        model.edu_id = self.jobDetail.eduid;
        model.edu_name = self.jobDetail.edu;
        model.city_id = self.jobDetail.cityid;
        model.city_name = self.jobDetail.city;
        model.job_desc = self.jobDetail.jobdesc;
        model.lever2ID = self.jobDetail.category_level2_id;
        model.skillrequirement_tagsNumber = self.jobDetail.jobskillrequirementscount;
        model.jobskillrequirements = self.jobDetail.jobskillrequirements;
        
        model.jobId = self.jobDetail.jobid;
    }
    
    DDBossPublishJobViewController *vc = [[DDBossPublishJobViewController alloc] initWithType:BossJobTypeEdit];
    vc.infoModel = model;
    vc.jobID = self.jobId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)hideButtonClick:(UIButton *)sender {

    [self markHiddenStatus];
}

#pragma mark
#pragma mark - Private Method

- (void)queryJobDetailInfo
{
    WEAKSELF
    
    [self.bossJobService queryMyselfJobInfoWithJobId:self.jobId SuccessBlock:^(id responseObject) {
        if ([weakSelf isValidateResponseData:responseObject]) {
            
            DDJobsDetail *detailInfo = [DDJobsDetail yy_modelWithJSON:responseObject[@"data"]];
            
            weakSelf.jobDetail = detailInfo;
            weakSelf.title = detailInfo.jobtitle;
            [weakSelf updateView];
            
        } else {
            [weakSelf responseUnValidate:responseObject];
        }
    } failBlock:^(id responseObject, NSError *error) {
        [weakSelf requestFaild];
    }];
}


- (void)markHiddenStatus
{
    NSMutableArray *tagidArray = [NSMutableArray array];
    if (self.jobDetail.jobskillrequirements.count!=0) {
        for (int i = 0; i<self.jobDetail.jobskillrequirements.count; i++) {
            [tagidArray addObject:self.jobDetail.jobskillrequirements[i][@"tagid"]];
        }
    }
    NSString *jsonStr;
    if (tagidArray.count !=0) {
        NSDictionary *paramsDiction  = @{@"tagsNum":[NSString stringWithFormat:@"%ld",(unsigned long)tagidArray.count],@"tagsIDs":tagidArray};
        NSData *data=[NSJSONSerialization dataWithJSONObject:paramsDiction options:NSJSONWritingPrettyPrinted error: nil];
        NSMutableData *jsonData=[NSMutableData dataWithData:data];
        jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else{
      jsonStr = @"";
    }
    WEAKSELF
    [self showLoading];
    
    NSDictionary *paraDic;
    
    if (!self.hideButton.selected) {
        paraDic = @{@"is_hidden":@"1",
                    @"job_id":self.jobId,@"skillrequirement_tags":jsonStr};
    } else {
        paraDic = @{@"is_hidden":@"0",
                    @"job_id":self.jobId,@"skillrequirement_tags":jsonStr};
    }
    
    [self.bossJobService editJobInfoWithDictionary:paraDic SuccessBlock:^(id responseObject) {

        [weakSelf hideLoading];

        if ([weakSelf isValidateResponseData:responseObject]) {
            
            weakSelf.hideButton.selected = !weakSelf.hideButton.selected;
            if (weakSelf.hideButton.selected) {
                [weakSelf showText:@"职位已隐藏"];

                [weakSelf.hideButton setTitle:@"开放职位" forState:UIControlStateNormal];
            } else {
                [weakSelf showText:@"职位已开放"];

                [weakSelf.hideButton setTitle:@"隐藏职位" forState:UIControlStateNormal];
            }
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf queryJobDetailInfo];
            });
            
        } else {
            [weakSelf responseUnValidate:responseObject];
        }
    } failBlock:^(id responseObject, NSError *error) {
        
        [weakSelf requestFaild];
    }];
}

/**
 *  刷新View数据
 */
- (void)updateView
{
    
    self.hideButton.selected = [self.jobDetail.ishidden isEqualToString:@"1"];
    
//    //head信息
//    _tableHeaderView.countSeeResumeLab.text = self.jobDetail.hits;
//    _tableHeaderView.countInterestLab.text = self.jobDetail.jobinterestedcount;
//    _tableHeaderView.countShareLab.text = self.jobDetail.hitsh5;
    
    // jobs信息
    DDJobDetailCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [cell updateJobDetailCellWithInfo:self.jobDetail];

    //boss Info
    DDBossDetailCell *bossCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    [bossCell.avatarImage sd_setImageWithURL:[NSURL URLWithString:[DDAPIGenerate imageURLWithPath:self.jobDetail.logo]] placeholderImage:[UIImage imageNamed:@"common_avatar"]];
    bossCell.nameLabel.text = self.jobDetail.employername;
    if ([self.jobDetail.employername length] < 1) {
        self.jobDetail.employername = @"未填写";
    }
    if ([self.jobDetail.companyshortname length] < 1) {
        self.jobDetail.companyshortname = @"未填写";
    }
    if ([self.jobDetail.position length] < 1) {
        self.jobDetail.position = @"未填写";
    }
    bossCell.personInfoLabel.text = [NSString stringWithFormat:@"%@ | %@ | %@",self.jobDetail.employername,self.jobDetail.companyshortname,self.jobDetail.position];
    bossCell.verifyImageView.hidden = ![self.jobDetail.is_employer_verified isEqualToString:@"1"];
    bossCell.publishedjobsButton.hidden = YES;

    // 团队介绍
    DDTeamDescriptionCell *teamCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    
    [teamCell updateTeamDescriptionCellWithInfo:self.jobDetail];
    
    CGFloat cellHeight = 50;
    CGFloat textWidth = kScreenWidth - (10*2 + 15*2);
    CGFloat textHeight = [DDUtils heightWithWidth:textWidth lineSpace:10 font:[UIFont systemFontOfSize:13] text:self.jobDetail.teamintro];
    
    
    if (self.jobDetail.teamintro.length > 0 && self.jobDetail.teamhighlights.count < 1) {
        cellHeight += textHeight + 15;
    }
    
    if ([self.jobDetail.teamhighlights count] > 0 && [self.jobDetail.teamhighlights count] < 5) {
        
        cellHeight += 55;
    } else if ([self.jobDetail.teamhighlights count] > 4 && [self.jobDetail.teamhighlights count] < 9) {
        
        cellHeight += 95;
    } else  {
        
        cellHeight -= 9;
    }
    
    cellHeight += (10 + textHeight);
    
    
    
    if ([self.rowHeightArray count] > 3) {
        [self.rowHeightArray replaceObjectAtIndex:2 withObject:@(cellHeight)];
    }
    
    // 职位描述
    DDJobDescriptionCell *jobCell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    
    [jobCell updateJobDescriptionCellWithInfo:self.jobDetail];
    
    CGFloat jobCellHeight = 50;
    CGFloat jobTextWidth = kScreenWidth - (10*2 + 15*2);
    CGFloat jobTextHeight = [DDUtils heightWithWidth:jobTextWidth lineSpace:10 font:[UIFont systemFontOfSize:13] text:self.jobDetail.jobdesc];
    
    jobCellHeight += jobTextHeight;
    jobCellHeight += 20;
    if ([self.rowHeightArray count] > 4) {
        [self.rowHeightArray replaceObjectAtIndex:3 withObject:@(jobCellHeight)];
    }
    
    // 公司信息
    [self.tableView reloadData];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.rowHeightArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self.rowHeightArray[indexPath.row] floatValue];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    if (indexPath.row == 0) {
        
        cell = (DDJobDetailCell *)[tableView dequeueReusableCellWithIdentifier:@"DDJobDetailCell"];
        
    } else if (indexPath.row == 1) {
        
        cell = (DDBossDetailCell *)[tableView dequeueReusableCellWithIdentifier:@"DDBossDetailCell"];
        
    } else if (indexPath.row == 2) {
        
        cell = (DDTeamDescriptionCell *)[tableView dequeueReusableCellWithIdentifier:@"DDTeamDescriptionCell"];
        
    } else if (indexPath.row == 3) {
        
        cell = (DDJobDescriptionCell *)[tableView dequeueReusableCellWithIdentifier:@"DDJobDescriptionCell"];
        
    } else if (indexPath.row == 4) {
        
        cell = (DDCompanyInfoCell *)[tableView dequeueReusableCellWithIdentifier:@"DDCompanyInfoCellID"];
        
        DDCompanyInfoCell *companycell = (DDCompanyInfoCell *)cell;
        
        if (self.jobDetail != nil) {
            
            companycell.model = self.jobDetail;
        }
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end
